﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
using System.Text;

using BartonExtension;

namespace WSServer
{
    public enum WSSocketStatus
    {
        kSocketIntializing,
        kSocketInitialized,
        kSocketStatusAuthorized,
        kSocketStatusTokenExpired,
        kSocketStatusClosed
    }
    public class WSSocket
    {
        const int MAX_MESSAGES_POOL_SIZE = 100;
        const int STATE_TIMEOUT = 30; //in sec

        const int BUFFER_SIZE = 1024;
        private WebSocket socket { get; set; }
        private double socket_status_on_changed_timetag { get; set; }
        private bool disposed = false;

        public WSSocketMessagePool messagePool { get; set; }
        public WSAccessToken token { get; set; }
        public string identifier { get; set; }
        public WSSocketStatus socket_status { get; set; }

        public void Dispose()
        {
            if(!disposed)
            {
                Dispose(true);
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }
            if (disposing)
            {
                // 清理托管资源
                if (socket != null)
                {
                    socket.Abort();
                    socket.Dispose();
                    socket = null;
                }
            }
            disposed = true;
        }

        public static WSSocket New(WebSocket socket)
        {
            WSSocket ws = new WSSocket(socket);
            return ws;
        }
        public WSSocket(WebSocket socket)
        {
            this.socket = socket;
            Initialize();
        }
        public void Initialize()
        {
            if(socket != null)
            {
                OnOpen();
            }
            messagePool = new WSSocketMessagePool(this.identifier);
            SetCurrentSocketStatus(WSSocketStatus.kSocketIntializing);
        }
        public async Task RegisterSocketEvents()
        {
            while (true)
            {
                ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[BUFFER_SIZE]);
                WebSocketReceiveResult result = await socket.ReceiveAsync(
                        buffer, CancellationToken.None);
                if (socket.State == WebSocketState.Open)
                {
                    await OnMessageReceived(buffer, result.MessageType);
                }
                else if(socket.State == WebSocketState.Closed)
                {
                    OnClose(socket.CloseStatus, socket.CloseStatusDescription);
                }
                else if(socket.State == WebSocketState.CloseReceived)
                {
                    OnClose(socket.CloseStatus, socket.CloseStatusDescription);
                }
                else
                {
                    break;
                }
            }
        }
        private async Task OnMessageReceived(ArraySegment<byte> message, System.Net.WebSockets.WebSocketMessageType type)
        {
            WSMessage ws_msg = new WSMessage()
            {
                message_time = DateTime.Now,
                message_type = type,
                content = message,
                socket = this
            };
            var result = await WSUtils.sharedInstance.ProcessMessage(ws_msg,
                msg_onRegisterService =>
                {
                    WSResponse response = new WSResponse()
                    {
                        identifier = this.identifier,
                        token = this.token,
                        type = WSResponseType.kWSResponseTypeDidSocketRegistered
                    };
                    Send<WSResponse>(response);
                    SetCurrentSocketStatus(WSSocketStatus.kSocketStatusAuthorized);
                },
                msg_onRequestToken =>
                {
                    this.AssignAccessCodeToSocket();
                    WSResponse response = new WSResponse()
                    {
                        identifier = this.identifier,
                        token = this.token,
                        type = WSResponseType.kWSResponseTypeDidTokenRefreshed
                    };
                    Send<WSResponse>(response);
                },
                msg_onReceviceMessage =>
                {
                    
                },
                msg_onReceiveMessageReceip =>
                {
                    WSResponseReceip receip = ws_msg.Get<WSResponseReceip>();

                });
            if (!result.isProcessedSuccess)
            {
                
            }
        }
        private void OnOpen()
        {
            this.AssignAccessCodeToSocket();
            WSSocketCollection.collection.Enqueue(this);
            SetCurrentSocketStatus(WSSocketStatus.kSocketInitialized);
        }
        private void OnClose(WebSocketCloseStatus? closeStatus, string closeStatusDescription)
        {
            SetCurrentSocketStatus(WSSocketStatus.kSocketStatusClosed);
            WSSocketCollection.collection.DeleteSocketWithIdentifier(this.identifier);
        }
        private void SetCurrentSocketStatus(WSSocketStatus status)
        {
            socket_status = status;
            socket_status_on_changed_timetag = DateTime.Now.GetTimeIntervalFrom1970WithDateTime();
        }
        public Task Send<T>(T obj)
        {
            try
            {
                string sendMessage = string.Empty;
                if (typeof(T) == typeof(int) || typeof(T) == typeof(string))
                    sendMessage = obj.ToString();
                else
                    sendMessage = obj.ToJson();
                var toSend = Encoding.UTF8.GetBytes(sendMessage);

                return this.socket.SendAsync(new ArraySegment<byte>(toSend), WebSocketMessageType.Text, true, CancellationToken.None);
            }
            catch (Exception e)
            {
                return Task.Factory.StartNew(() => { });
            }
        }
        public bool ShouldBeCleaned()
        {
            if (this.socket_status == WSSocketStatus.kSocketStatusClosed)
                return true;
            if(this.socket_status == WSSocketStatus.kSocketStatusTokenExpired && (DateTime.Now.GetTimeIntervalFrom1970WithDateTime() - socket_status_on_changed_timetag) >= STATE_TIMEOUT)
                return true;
            if (this.socket_status == WSSocketStatus.kSocketIntializing && (DateTime.Now.GetTimeIntervalFrom1970WithDateTime() - socket_status_on_changed_timetag) >= STATE_TIMEOUT)
                return true;
            if (this.socket_status == WSSocketStatus.kSocketInitialized && (DateTime.Now.GetTimeIntervalFrom1970WithDateTime() - socket_status_on_changed_timetag) >= STATE_TIMEOUT)
                return true;
            return false;
        }
    }
}
